<template>
  <div class="NowPayDialog">
    <el-dialog title="费用结算" :visible.sync="$parent.NowPayFlag" width="30%" v-dialogDrag border @close="closeDialog()">
      <el-form :model="datalist" :rules="rules" :inline="true" label-width="120px" ref="NowPay" :disabled="saveFlag">
        <!--<el-row :gutter="5">-->
        <!--<el-form-item label="结算项目：" prop="id" >-->
        <!--<el-select v-model="datalist.chargeSettle.settleTypeCode" placeholder="请选择"  style="width: 120px;">-->
        <!--<el-option-->
        <!--v-for="item in dictionary.settle_type"-->
        <!--:key="item.dataCode"-->
        <!--:label="item.dataText"-->
        <!--:value="item.dataCode"-->
        <!--:disabled="item.disableState?true:false"/>-->
        <!--</el-select>-->
        <!--</el-form-item>-->
        <!--</el-row>-->
        <el-row :gutter="5">
          <!--<el-form-item label="结算日期：" >
            <el-date-picker v-model="datalist.chargeSettle.settleTime" format="yyyy-MM-dd HH:mm" type="datetime" placeholder="选择日期时间"></el-date-picker>
          </el-form-item>-->
          <el-form-item label="经办人：" prop="settleUser">
            <el-input v-model="datalist.chargeSettle.settleUser" :disabled="true"></el-input>
          </el-form-item>
        </el-row>
        <!--<el-row :gutter="5">-->
          <!--<el-form-item label="发票代码：">-->
            <!--<el-input v-model="datalist.chargeSettle.invoiceCode" :maxlength="20"></el-input>-->
          <!--</el-form-item>-->
          <!--<el-form-item label="发票号：">-->
            <!--<el-input v-model="datalist.chargeSettle.invoiceNo" :maxlength="20"></el-input>-->
          <!--</el-form-item>-->
        <!--</el-row>-->
        <el-row :gutter="5">
          <el-form-item label="收据号：">
            <el-input v-model="datalist.chargeSettle.receiptNo" :maxlength="20"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="备注：">
            <el-input type="textarea" v-model="datalist.chargeSettle.Remark" style="width: 534px;"></el-input>
          </el-form-item>
        </el-row>
        <hr>
        <el-row :gutter="5" v-for="(item,index) in datalist.chargeSettleWay" :key="item.dataCode">
          <el-form-item label="支付方式：">

            <el-select v-model="item.payTypeCode" placeholder="请选择" @change="settleWay" style="width: 120px;">
              <el-option
                v-for="item in dictionary.pay_type"
                :key="item.dataCode"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState?true:false"/>
            </el-select>
          </el-form-item>
          <el-form-item label="付款金额：">
            <el-input  onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"   v-model="item.payCharge"></el-input>
          </el-form-item>
          <i class="el-icon-check" v-show="item.payCharge"></i>
          <i class="el-icon-close" v-show="!item.payCharge"></i>
          <i class="el-icon-remove" v-if="datalist.chargeSettleWay && datalist.chargeSettleWay.length>1" style="font-size:32px;color:cornflowerblue;vertical-align: sub;margin-right: 5px;"
             @click="Chargedelete(index)"></i>
          <el-form-item label="挂账单位" v-if="item.payTypeCode=='4'">
            <el-select v-model="item.accountUnit" onkeydown="return (event.keyCode!=8)" allow-create  clearable filterable
                       placeholder="请选择或填写">
              <el-option
                v-for="item in dictionary.account_unit"
                :key="item.dataCode"
                :label="item.dataText"
                :value="item.dataText"/>
            </el-select>
          </el-form-item>
        </el-row>
        <p style="text-align: right;position: relative;">
          <i class="el-icon-circle-plus"
             @click="addChargeType"
             style="font-size:32px;color:cornflowerblue;position: absolute;top: -58px;right: 0px;"></i>
        </p>
        <el-row class="font16" style="text-align: right">
          合计：<span class="totalw">{{total}}</span>
        </el-row>

        <hr>
        <el-row class="font16">
          <div style="line-height: 40px;text-align: right">
            总金额:<span class="totalw">{{ Charge.Settled }}</span>元，
            优惠:<span class="totalw">{{ Charge.discountCharge }}</span>元，
            减免:<span class="totalw">{{ Charge.benefitCharge }}</span>元，
            待结算金额:<span class="totalw">{{ Charge.realityCharge }}</span>元
          </div>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button type="primary"  @click="Save()">提交缴费</el-button>
        <el-button type="primary" plain   @click="$parent.NowPayFlag = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
    import * as Type from '@/api/service'
    import {validPhone} from '@/utils/validate'
    import {dataFormate} from '@/utils/index'
    import {toFixed} from "@/utils/tofixed"
    export default {
        name: "NowPayDialog",
        props: {
            NowPayFlag: {
                type: Boolean
            },
            multipleSelection: {
                type: Array,
                require: true
            },
            businessCode: {
                type: String,
                default: ""
            }, totalCharge: {
                type: Number,
                default: 0
            }, //要传递的按钮权限
          btnRight: {
            type: Object,
            default: function () {
              return {
                btnNowPaySave: true,  //提交保存
                btnNowPayCancel: true,//取消
              }
            }
          }

        }, created() {
            //加载挂账字典
            let postData = [
                "account_unit"
            ]
            let this_create = this;
            Type['loadDictionary'](postData).then(response => {
                const {data} = response;
                if (!data) {
                    this_create.$message('数据读取失败')
                    return
                }
                this_create.dictionary.account_unit = data.account_unit;
            }).catch(error => {
                this_create.$message(error)
            })
        },
        mounted() {
          //按钮权限 按钮的权限来自于父窗口的权限，这里不是从route传过来的，在此处关闭
          //   this.btnRight = this.$route.meta.buttons;
            this.$store.dispatch('user/getdictionary').then((res) => {
                //获取字典数据
                this.dictionary = res;
                this.$set(this.dictionary, res)
            }).catch(()=>console.log('promise catch err'));
        //console.log(this.Charge,'   .....',this.datalist.chargeSettleWay[0])
        },
        data() {
            return {
                saveFlag: false,     //保存过程中不可更改,true为正在保存
                dictionary: {},      //字典
                datalist: {
                    chargeSettle: {
                        "id": "",
                        "settleTime": Date(),
                        "payCharge": 0,
                        "settleTypeCode": "",
                        "invoiceCode": "",
                        "invoiceNo": "",
                        "receiptNo": "",
                        "settleBatchNo": "",
                        "settleUser": "",
                        "verifyState": 0,
                        "Remark": "",
                        "version": 0
                    },
                    "chargeSettleWay": [        //付款方式
                        {
                            "payCharge": 0,
                            "payTypeCode": "",
                            "settleWayName": "",
                            "accountUnit": ""//挂账单位
                        },

                    ],
                },
                rules: {
                    id: [
                        {required: true, message: '请选择结算项目', trigger: 'blur'},
                    ],
                    settleTime: [
                        {required: true, message: '请选择结算日期', trigger: 'blur'}//这里需要用到全局变量
                    ],
                    settleUser: [
                        {required: true, message: '请输入经办人', trigger: 'blur'}
                    ],

                },
                formLabelWidth: '120px',
                onpresscTime:0,  //  阻止短时间内连续点击
                // btnlimits: {//按钮权限
                // btnNowPaySave: true,  //提交保存
                // btnNowPayCancel: true,//取消
                // }
            }
        },
        watch: {
            '$parent.NowPayFlag'() {
                this.datalist.chargeSettle.settleUser = this.$store.getters.userInfo.fullName
                this.datalist.chargeSettle.settleTime = dataFormate(Date())
                this.$parent.NowPayFlag = this.NowPayFlag
                if (this.$parent.NowPayFlag == false) {
                    this.$nextTick(() => {
                        this.$refs.NowPay.resetFields();
                    })
                    let obj = {
                        chargeSettle: {
                            "id": "",
                            "settleTime": dataFormate(Date()),
                            "payCharge": "",
                            "settleWay": "",
                            "invoiceCode": "",
                            "invoiceNo": "",
                            "receiptNo": "",
                            "settleBatchNo": "",
                            "settleUser": this.$store.getters.name,
                            "verifyState": "",
                            "version": 0
                        },
                        chargeSettleWay: [        //付款方式
                            {
                                "payCharge": 0,
                                "payTypeCode": "",
                                "settleWayName": ""
                            }
                        ],
                    }
                    this.datalist.chargeSettle = obj.chargeSettle
                    this.datalist.chargeSettleWay = obj.chargeSettleWay
                    this.$parent.chargeSettle = obj.chargeSettle
                    this.$parent.chargeSettleWay = obj.chargeSettleWay
                  /*触发刷新*/
                  this.$emit('refresh')
                }
            }
        },
        methods: {
            //支付方式
            settleWay() {
                let arry = []
                this.datalist.chargeSettleWay.forEach(item => {
                    //挂账
                    // if (item.payTypeCode == 4) {
                    //     this.$message('增加挂账');
                    // }
                    if (arry.indexOf(item.payTypeCode) == -1) {
                        arry.push(item.payTypeCode)
                    } else {
                        item.payTypeCode = ""
                        this.$message("该付款方式已存在，请选择其他方式")
                    }
                })
            },
            Chargedelete(index) {
                this.datalist.chargeSettleWay.splice(index, 1)
            },
            addChargeType() {
                if (this.datalist.chargeSettleWay.length > this.dictionary.pay_type.length) {
                    this.$message("已加载所有付款方式")
                    return
                }
                {
                    this.datalist.chargeSettleWay.push({
                        "payCharge": 0,
                        "payTypeCode": "",
                        "payType": ""
                    },)
                }
            },
            //保存
            Save() {
              if ((Date.now() - this.onpresscTime) > 2000) {
                this.onpresscTime = Date.now()
                console.log(Date.now())
              }else{
                return
              }
                let returnFlag = true
              let guazhuangCode
              if (this.dictionary.pay_type && this.dictionary.pay_type.length) {
                  this.dictionary.pay_type.forEach(item=>{
                    if (item.dataText.indexOf("挂账")>-1) {
                      guazhuangCode = item.dataCode
                    }
                  })
              }
                if (this.datalist.chargeSettleWay && this.datalist.chargeSettleWay.length){
                  this.datalist.chargeSettleWay.forEach(item => {
                    if (!item.payTypeCode) {
                      this.$message("未选择支付方式")
                      returnFlag = false
                    }
                    if (item.payTypeCode ==guazhuangCode && this.datalist.chargeSettleWay.length>1) {
                      this.$message("挂账与其他付款方式不能并存")
                      returnFlag = false
                    }
                  })
                  if (!returnFlag) {
                    return
                  }
                }else{
                  return
                }

                // if (this.total == 0) {
                //     this.$message("付款金额不能为0")
                //     return
                // }
                this.saveFlag = true;
                let this_local = this;
                let idarry = []
                this.multipleSelection.forEach(item => {
                    if (item.id) {
                        let obj = {}
                        obj.id = item.id
                        obj.version = item.version
                        idarry.push(obj)
                    }
                })
                let settleCharge = 0;
                this.datalist.chargeSettleWay.forEach(item => {
                    this.dictionary.pay_type.forEach(n => {
                        if (n.dataCode == item.payTypeCode) {
                            item.payType = n.dataText
                            settleCharge += Number(item.payCharge)
                        }
                    })
                })
                settleCharge = toFixed(settleCharge,2)
                let chargeSettle = this.datalist.chargeSettle;
                let chargeSettlePay = this.datalist.chargeSettleWay;
                //更新结算时间为当前时间
                if (chargeSettle) {
                    chargeSettle.settleTime = dataFormate(new Date());
                }
                console.log(this.$parent.businessCode,22222);
                console.log(this.businessCode,66666);
                console.log(this_local.businessCode,444444);
                chargeSettle.businessCode = this_local.businessCode;
                chargeSettle.settleCharge = settleCharge;
                if (chargeSettle && chargeSettle.length > 0) {
                    chargeSettle.forEach(item => {
                        delete item.settleWayName;
                    })
                }
                let postData = {
                    "ids": idarry,
                    "chargeSettle": chargeSettle,
                    "chargeSettlePay": chargeSettlePay
                }
                Type['savechargesettletosettleaccounts'](postData).then(response => {
                    let result = response;
                    if (result){
                      this.$message("保存成功")
                      this.$parent.NowPayFlag = false
                    }
                  this.saveFlag = false;
                }).catch(error => {
                    this.$message(error)
                  this.saveFlag = false;
                })
                this.$emit('sendmsg',this_local.businessCode);
                //this.$parent.businessCode="";
            },
            closeDialog() {
                this.$parent.NowPayFlag = false;
            },
        },
        computed: {
            total() {
                let total = 0;
                if (this.datalist.chargeSettleWay.length > 0) {
                    this.datalist.chargeSettleWay.forEach(item => {
                        if (item.payCharge) {
                            total += Number(item.payCharge)
                        }
                    })
                }
                total = toFixed(total,2)
                return total
            },
            Charge() {
                let charge = {total: 0, Settled: 0, discountCharge: 0, benefitCharge: 0, realityCharge: 0}
                if (this.multipleSelection) {
                    this.multipleSelection.forEach(n => {
                      if (n.itemCharge){
                        charge.total += Number(n.itemCharge);
                      }
                      if (n.asSettled == 0) {  //未结算
                            charge.Settled += Number(n.itemCharge);
                            charge.discountCharge += Number(n.discountCharge);
                            charge.benefitCharge += Number(n.benefitCharge);
                            charge.realityCharge += Number(n.realityCharge);
                        }

                    })
                }

              for (let i in charge) {
                charge[i] = toFixed(charge[i],2)
              }
              //console.log(charge,'000000000000/');
               this.datalist.chargeSettleWay[0].payCharge=charge.realityCharge;
               return charge
            }
        }
    }
</script>
<style>
  .NowPayDialog .el-dialog__title, .NowPayDialog .el-dialog__headerbtn .el-dialog__close {
    color: white;
  }

  .NowPayDialog .el-dialog {
    min-width: 800px !important;
  }

  .NowPayDialog .el-input, .NowPayDialog .el-select, .NowPayDialog .el-form-item__content {
    width: 200px;
  }

  .NowPayDialog .el-textarea__inner {
    width: 534px;
  }

  .NowPayDialog .el-icon-check[data-v-7f39c8b7]:before {
    margin-left: 0em;
  }
</style>
<style scoped>
  @media screen and (max-width: 300px) {
    body {
      background-color: lightblue;
    }
  }

  .tablewrapper {
    display: flex;
  }

  .tablewrapper .table {
    display: inline-block;
    flex: 1;
    width: 50%;
    padding: 0 1em;
    border: 1px solid rgb(220, 223, 230);
  }

  .tablewrapper .table .title {
    font-size: 1rem;
    font-weight: 700;
    line-height: 3rem;
  }

  .tablewrapper .table .tablecont {
    padding: 1em;
    line-height: 2em;
    text-indent: 2em;
  }

  .el-icon-close:before {
    color: red;
    font-size: 1.5em;
    line-height: 2em;
  }

  .el-icon-check:before {
    color: green;
    font-size: 1.5em;
    line-height: 2em;
    margin-left: 1em;
  }
  .totalw {
    display: inline-block;
    width: 80px;
    font-weight:600;
  }
</style>
